/**   
* @Title: PullToRefreshListViewNews.java 
* @Package com.esun.cheetah.view.personal.lotteryinfoact.PullToRefreshListViewNews
* @Description: (自定义ListView类) 
* @Author 孔祥攀 <br/>   
* @Date 2012-3-30 上午11:08:42
* Copyright (C) 2012 Shenzhen E-sun Sky Net Technology Co.,ltd.
*/
package com.esun.cheetah.view.personal.lotteryinfoact;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.esun.cheetah.R;

/**
 * 
 * @Package com.esun.cheetah.view.personal.lotteryinfoact.PullToRefreshListViewNews
 * @ClassName: PullToRefreshListViewNews
 * @Description: TODO(自定义的可拖动listview类)
 * @author 孔祥攀 <br/>
 * @date 2012-3-30 上午11:08:42
 *
 */
public class PullToRefreshListViewNews extends ListView implements OnScrollListener {

	// 刷新过程中4个状态1==准备,2==拉动刷新,3==释放刷新,4==刷新中
	private static final int TAP_TO_REFRESH = 1;
	private static final int PULL_TO_REFRESH = 2;
	private static final int RELEASE_TO_REFRESH = 3;
	private static final int REFRESHING = 4;

//	private static final String TAG = "PullToRefreshListView";// test

	private OnRefreshListener mOnRefreshListener;
	private OnBottomListener mOnBottomListener;
	private OnPrepareForRefreshListener mOnPrepareForRefreshListener;
	

	private OnScrollListener mOnScrollListener;
	private LayoutInflater mInflater;

	private LinearLayout mRefreshView;
	private TextView mRefreshViewText;
	private ImageView mRefreshViewImage;
	private ProgressBar mRefreshViewProgress;
	private TextView mRefreshViewLastUpdated;

	private int mCurrentScrollState;// scroll滚动状态
	private int mRefreshState;// 刷新状态

	private RotateAnimation mFlipAnimation;
	private RotateAnimation mReverseFlipAnimation;

	private int mRefreshViewHeight;
	private int mRefreshOriginalTopPadding;
	private int mLastMotionY;

	private boolean setBack = true;

	public PullToRefreshListViewNews(Context context) {
		super(context);
		init(context);
	}

	public PullToRefreshListViewNews(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public PullToRefreshListViewNews(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	private void init(Context context) {
		// Load all of the animations we need in code rather than through XML
		// 滑动效果
		mFlipAnimation = new RotateAnimation(0, -180,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		mFlipAnimation.setInterpolator(new LinearInterpolator());
		mFlipAnimation.setDuration(250);
		mFlipAnimation.setFillAfter(true);
		// 箭头颠倒效果
		mReverseFlipAnimation = new RotateAnimation(-180, 0,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		mReverseFlipAnimation.setInterpolator(new LinearInterpolator());
		mReverseFlipAnimation.setDuration(250);
		mReverseFlipAnimation.setFillAfter(true);

		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		mRefreshView = (LinearLayout) mInflater.inflate(R.layout.pull_to_refresh_header, null);
		
		mRefreshViewText = (TextView) mRefreshView.findViewById(R.id.pull_to_refresh_text);
		mRefreshViewText.setTextColor(0xff121225);
		mRefreshViewImage = (ImageView) mRefreshView.findViewById(R.id.pull_to_refresh_image);
		mRefreshViewProgress = (ProgressBar) mRefreshView.findViewById(R.id.pull_to_refresh_progress);
		mRefreshViewLastUpdated = (TextView) mRefreshView.findViewById(R.id.pull_to_refresh_updated_at);

		mRefreshViewImage.setMinimumHeight(50);
		mRefreshView.setOnClickListener(new OnClickRefreshListener());
		mRefreshOriginalTopPadding = mRefreshView.getPaddingTop();

		mRefreshState = TAP_TO_REFRESH;
		addHeaderView(mRefreshView);

		super.setOnScrollListener(this);

		measureView(mRefreshView);
		mRefreshViewHeight = mRefreshView.getMeasuredHeight();
		
		mRefreshViewProgress.setVisibility(View.VISIBLE);
	}

	@Override
	protected void onAttachedToWindow() {
		setSelection(1);
	}

	@Override
	public void setAdapter(ListAdapter adapter) {
		super.setAdapter(adapter);

		setSelection(1);
	}

	@Override
	public void setOnScrollListener(AbsListView.OnScrollListener l) {
		mOnScrollListener = l;
	}

	public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
		mOnRefreshListener = onRefreshListener;
	}

	public void setOnBottomListener(OnBottomListener onBottomListener) {
		mOnBottomListener = onBottomListener;
	}
	public void setOnPrepareForRefreshListener(OnPrepareForRefreshListener OnPrepareForRefreshListener) {
		mOnPrepareForRefreshListener = OnPrepareForRefreshListener;
	}

	public void setLastUpdated(CharSequence lastUpdated) {
		if (lastUpdated != null) {
			mRefreshViewLastUpdated.setVisibility(View.VISIBLE);
			mRefreshViewLastUpdated.setText(lastUpdated);
		} else {
			mRefreshViewLastUpdated.setVisibility(View.GONE);
		}
	}

	@SuppressWarnings("unused")
	private void scrollListBy(int distance, int duration) {
		try {
			Method method = ListView.class.getMethod("smoothScrollBy",
					Integer.TYPE, Integer.TYPE);
			method.invoke(this, distance + 1, duration);
		} catch (NoSuchMethodException e) {
			// If smoothScrollBy is not available (< 2.2)
			setSelection(1);
		} catch (IllegalArgumentException e) {
			throw e;
		} catch (IllegalAccessException e) {
//			System.err.println("unexpected " + e);
		} catch (InvocationTargetException e) {
//			System.err.println("unexpected " + e);
		}
	}
	//去掉顶部刷新方法
	public void removeRefreshHeaderView() {
		// TODO Auto-generated method stub
		super.removeHeaderView(mRefreshView);
	}
	
	//获取刷新高度
	public int getHeaderViewHeight(){
		return mRefreshView.getHeight();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		final int y = (int) event.getY();

		switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				if (!isVerticalScrollBarEnabled()) {
					setVerticalScrollBarEnabled(true);
				}
				if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) {
					if (mRefreshView.getBottom() > mRefreshViewHeight
							|| mRefreshView.getTop() >= 0
							&& mRefreshState == RELEASE_TO_REFRESH) {
						// Initiate the refresh
						mRefreshState = REFRESHING;
						prepareForRefresh();
						onRefresh();
					} else if (mRefreshView.getBottom() < mRefreshViewHeight) {
						// Abort refresh and scroll down below the refresh view
						resetHeader();
						setSelection(1);
					}
				}
				if (setBack == false && getFirstVisiblePosition() != 0) {
					setSelection(1);
					setBack = true;
				}
				break;

			case MotionEvent.ACTION_DOWN:
				mLastMotionY = y;
				break;

			case MotionEvent.ACTION_MOVE:
				applyHeaderPadding(event);
				break;

			default:
				break;
		}
		return super.onTouchEvent(event);
	}

	private void applyHeaderPadding(MotionEvent ev) {
		final int historySize = ev.getHistorySize();

		// Workaround for getPointerCount() which is unavailable in 1.5
		// (it's always 1 in 1.5)
		int pointerCount = 1;
		try {
			Method method = MotionEvent.class.getMethod("getPointerCount");
			pointerCount = (Integer) method.invoke(ev);
		} catch (NoSuchMethodException e) {
			pointerCount = 1;
		} catch (IllegalArgumentException e) {
			throw e;
		} catch (IllegalAccessException e) {
//			System.err.println("unexpected " + e);
		} catch (InvocationTargetException e) {
//			System.err.println("unexpected " + e);
		}

		for (int h = 0; h < historySize; h++) {
			for (int p = 0; p < pointerCount; p++) {
				if (mRefreshState == RELEASE_TO_REFRESH) {
					if (isVerticalFadingEdgeEnabled()) {
						setVerticalScrollBarEnabled(false);
					}

					int historicalY = 0;
					try {
						// For Android > 2.0
						Method method = MotionEvent.class.getMethod(
								"getHistoricalY", Integer.TYPE, Integer.TYPE);
						historicalY = ((Float) method.invoke(ev, p, h))
								.intValue();
					} catch (NoSuchMethodException e) {
						// For Android < 2.0
						historicalY = (int) (ev.getHistoricalY(h));
					} catch (IllegalArgumentException e) {
						throw e;
					} catch (IllegalAccessException e) {
//						System.err.println("unexpected " + e);
					} catch (InvocationTargetException e) {
//						System.err.println("unexpected " + e);
					}

					// Calculate the padding to apply, we divide by 1.7 to
					// simulate a more resistant effect during pull.
					int topPadding = (int) (((historicalY - mLastMotionY) - mRefreshViewHeight) / 5);

					mRefreshView.setPadding(mRefreshView.getPaddingLeft(),
							topPadding, mRefreshView.getPaddingRight(),
							mRefreshView.getPaddingBottom());
				}
			}
		}
	}

	/**
	 * Sets the header padding back to original size.
	 */
	private void resetHeaderPadding() {
		mRefreshView.setPadding(mRefreshView.getPaddingLeft(),
				mRefreshOriginalTopPadding, mRefreshView.getPaddingRight(),
				mRefreshView.getPaddingBottom());
	}

	/**
	 * Resets the header to the original state.
	 */
	private void resetHeader() {
		if (mRefreshState != TAP_TO_REFRESH) {
			mRefreshState = TAP_TO_REFRESH;

			resetHeaderPadding();

			// Set refresh view text to the pull label
			mRefreshViewText.setText(R.string.pull_to_refresh_tap_label);
			// Replace refresh drawable with arrow drawable
			mRefreshViewImage
					.setImageResource(R.drawable.ic_pulltorefresh_arrow);
			// Clear the full rotation animation
			mRefreshViewImage.clearAnimation();
			// Hide progress bar and arrow.
			mRefreshViewImage.setVisibility(View.GONE);
			mRefreshViewProgress.setVisibility(View.GONE);
		}
	}

	private void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}

		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
					MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0,
					MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// When the refresh view is completely visible, change the text to say
		// "Release to refresh..." and flip the arrow drawable.
		if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL
				&& mRefreshState != REFRESHING) {
			if (firstVisibleItem == 0) {
				mRefreshViewImage.setVisibility(View.VISIBLE);
				if ((mRefreshView.getBottom() > mRefreshViewHeight + 20 || mRefreshView.getTop() >= 0) && mRefreshState != RELEASE_TO_REFRESH) {
					mRefreshViewText.setText(R.string.pull_to_refresh_release_label);
					mRefreshViewImage.clearAnimation();
					mRefreshViewImage.startAnimation(mFlipAnimation);
					mRefreshState = RELEASE_TO_REFRESH;
//					Log.i("kongxp===>", "state change=====>" + mRefreshState);
				} else if (mRefreshView.getBottom() < mRefreshViewHeight + 20
						&& mRefreshState != PULL_TO_REFRESH) {
					mRefreshViewText
							.setText(R.string.pull_to_refresh_pull_label);
//					Log.i("kongxp===>", "state change=====>" + mRefreshState);
					setBack = false;
					if (mRefreshState != TAP_TO_REFRESH) {
						mRefreshViewImage.clearAnimation();
						mRefreshViewImage.startAnimation(mReverseFlipAnimation);
					}
					mRefreshState = PULL_TO_REFRESH;
//					Log.i("kongxp===>", "state change=====>" + mRefreshState);
				}
			} else {
				mRefreshViewImage.setVisibility(View.GONE);
				resetHeader();
			}
		} else if (mCurrentScrollState == SCROLL_STATE_FLING
				&& firstVisibleItem == 0 && mRefreshState != REFRESHING) {
			setSelection(1);
		}

		if (firstVisibleItem + visibleItemCount == totalItemCount) {
			onBottom();
		}

		if (mOnScrollListener != null) {
			mOnScrollListener.onScroll(view, firstVisibleItem,
					visibleItemCount, totalItemCount);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		mCurrentScrollState = scrollState;

		if (mOnScrollListener != null) {
			mOnScrollListener.onScrollStateChanged(view, scrollState);
		}
	}

	public void prepareForRefresh() {
		System.out.println("prepareForRefresh");
		mOnPrepareForRefreshListener.onPrepareForRefresh();
		resetHeaderPadding();

		mRefreshViewImage.setVisibility(View.GONE);
		// We need this hack, otherwise it will keep the previous drawable.
		mRefreshViewImage.setImageDrawable(null);
		mRefreshViewProgress.setVisibility(View.VISIBLE);

		// Set refresh view text to the refreshing label
		mRefreshViewText.setText(R.string.pull_to_refresh_refreshing_label);

		mRefreshState = REFRESHING;
//		Log.d("kongxp===>", "state change=====>" + mRefreshState);
	}

	public void onRefresh() {
//		Log.d(TAG, "onRefresh");
		if (mOnRefreshListener != null) {
//			Log.d(TAG, "refreshing....");
			mOnRefreshListener.onRefresh();
		}
	}

	public void onBottom() {
//		Log.d(TAG, "onBottom");
			if (mOnBottomListener != null) {
				mOnBottomListener.onBottom();
		}
	}

	public void onRefreshComplete(CharSequence lastUpdated) {
		setLastUpdated(lastUpdated);
		onRefreshComplete();
	}

	public void onRefreshComplete() {
//		Log.d(TAG, "onRefreshComplete");
//		Log.d(TAG, "" + mRefreshState);
		resetHeader();

		// If refresh view is visible when loading completes, scroll down to
		// the next item.
		if (mRefreshView.getBottom() > 0) {
//			Log.d(TAG, "setselection (1)");
			invalidateViews();
			setSelection(1);
		}
	}

	private class OnClickRefreshListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (mRefreshState != REFRESHING) {
				prepareForRefresh();
				onRefresh();
			}
		}
	}

	public interface OnRefreshListener {

		public void onRefresh();

		void onClick(View v);
	}

	public interface OnBottomListener {
		public void onBottom();
	}
	
	public interface OnPrepareForRefreshListener {
		public void onPrepareForRefresh();
	}
}
